<template>
  <view class="page-container">
    <!-- 顶部导航栏 -->
    <uni-nav-bar
      :border="false"
      title="创建下载"
      fixed
      left-icon="back"
      @clickLeft="goBack"
    />

    <view class="content">
      <view class="form-container">
        <!-- 开始日期 -->
        <view class="form-item" @click="showStartDatePicker">
          <text class="form-label">开始日期</text>
          <view class="form-value">
            <text :class="{ placeholder: !startDate }">
              {{ startDate || "选择" }}
            </text>
            <uni-icons type="right" size="16" color="#999"></uni-icons>
          </view>
        </view>

        <!-- 开始时间 -->
        <view class="form-item" @click="showStartTimePicker">
          <text class="form-label">开始时间</text>
          <view class="form-value">
            <text :class="{ placeholder: !startTime }">
              {{ startTime || "选择" }}
            </text>
            <uni-icons type="right" size="16" color="#999"></uni-icons>
          </view>
        </view>

        <!-- 结束日期 -->
        <view class="form-item" @click="showEndDatePicker">
          <text class="form-label">结束日期</text>
          <view class="form-value">
            <text :class="{ placeholder: !endDate }">
              {{ endDate || "选择" }}
            </text>
            <uni-icons type="right" size="16" color="#999"></uni-icons>
          </view>
        </view>

        <!-- 结束时间 -->
        <view class="form-item" @click="showEndTimePicker">
          <text class="form-label">结束时间</text>
          <view class="form-value">
            <text :class="{ placeholder: !endTime }">
              {{ endTime || "选择" }}
            </text>
            <uni-icons type="right" size="16" color="#999"></uni-icons>
          </view>
        </view>

        <!-- 接收邮箱 -->
        <view class="form-item input-item">
          <text class="form-label">接收邮箱</text>
          <input
            class="form-input"
            type="text"
            v-model="email"
            placeholder="请输入邮箱"
            placeholder-class="input-placeholder"
          />
        </view>

        <!-- 数据类型选择 -->
        <view class="type-section">
          <view
            v-for="item in typeList"
            :key="item"
            class="type-item"
            :class="{ active: item === selectedType }"
            @click="selectType(item)"
          >
            <text class="type-text">{{ item }}</text>
            <uni-icons
              v-if="item === selectedType"
              type="checkmarkempty"
              color="#fabc02"
            ></uni-icons>
          </view>
        </view>
      </view>

      <!-- 底部按钮 -->
      <view class="bottom-actions">
        <view class="action-btn reset-btn" @click="handleReset">
          <text>重置</text>
        </view>
        <view class="action-btn submit-btn" @click="handleSubmit">
          <text>提交</text>
        </view>
      </view>
    </view>

    <!-- 日期选择器 -->
    <uni-popup ref="datePickerRef" type="bottom">
      <view class="picker-container">
        <view class="picker-header">
          <text class="picker-reset" @click="resetDatePicker">重置</text>
          <text class="picker-title">选择日期</text>
          <text class="picker-confirm" @click="confirmDate">确定</text>
        </view>
        <picker-view
          :value="datePickerValue"
          @change="onDatePickerChange"
          class="picker-view"
          :indicator-style="indicatorStyle"
        >
          <picker-view-column>
            <view v-for="year in years" :key="year" class="picker-item">
              {{ year }}年
            </view>
          </picker-view-column>
          <picker-view-column>
            <view v-for="month in months" :key="month" class="picker-item">
              {{ month }}月
            </view>
          </picker-view-column>
          <picker-view-column>
            <view v-for="day in days" :key="day" class="picker-item">
              {{ day }}日
            </view>
          </picker-view-column>
        </picker-view>
      </view>
    </uni-popup>

    <!-- 时间选择器 -->
    <uni-popup ref="timePickerRef" type="bottom">
      <view class="picker-container">
        <view class="picker-header">
          <text class="picker-reset" @click="resetTimePicker">重置</text>
          <text class="picker-title">选择时间</text>
          <text class="picker-confirm" @click="confirmTime">确定</text>
        </view>
        <picker-view
          :value="timePickerValue"
          @change="onTimePickerChange"
          class="picker-view"
          :indicator-style="indicatorStyle"
        >
          <picker-view-column>
            <view v-for="hour in hours" :key="hour" class="picker-item">
              {{ hour }}时
            </view>
          </picker-view-column>
          <picker-view-column>
            <view v-for="minute in minutes" :key="minute" class="picker-item">
              {{ minute }}分
            </view>
          </picker-view-column>
          <picker-view-column>
            <view v-for="second in seconds" :key="second" class="picker-item">
              {{ second }}秒
            </view>
          </picker-view-column>
        </picker-view>
      </view>
    </uni-popup>
  </view>
</template>

<script setup>
import { ref, computed } from "vue";

// 选择器引用
const datePickerRef = ref(null);
const timePickerRef = ref(null);

// 表单数据
const startDate = ref("");
const startTime = ref("");
const endDate = ref("");
const endTime = ref("");
const email = ref("");

// 数据类型列表
const typeList = ref(["订单", "积分", "退款", "应收额"]);
const selectedType = ref("订单");

// 当前选择的是哪个字段
const currentDateField = ref("");
const currentTimeField = ref("");

// 日期选择器数据
const years = ref([]);
const months = ref([]);
const days = ref([]);
const datePickerValue = ref([0, 0, 0]);

// 时间选择器数据
const hours = ref([]);
const minutes = ref([]);
const seconds = ref([]);
const timePickerValue = ref([0, 0, 0]);

// 选择器指示器样式
const indicatorStyle = ref(
  "height: 68rpx; background-color: rgba(250, 188, 2, 0.1);",
);

// 初始化日期数据
const initDateData = () => {
  const currentYear = new Date().getFullYear();
  years.value = [];
  for (let i = currentYear - 5; i <= currentYear + 5; i++) {
    years.value.push(i);
  }

  months.value = [];
  for (let i = 1; i <= 12; i++) {
    months.value.push(String(i).padStart(2, "0"));
  }

  updateDays(currentYear, 1);
};

// 更新天数
const updateDays = (year, month) => {
  const daysInMonth = new Date(year, month, 0).getDate();
  days.value = [];
  for (let i = 1; i <= daysInMonth; i++) {
    days.value.push(String(i).padStart(2, "0"));
  }
};

// 初始化时间数据
const initTimeData = () => {
  hours.value = [];
  for (let i = 0; i <= 23; i++) {
    hours.value.push(String(i).padStart(2, "0"));
  }

  minutes.value = [];
  for (let i = 0; i <= 59; i++) {
    minutes.value.push(String(i).padStart(2, "0"));
  }

  seconds.value = [];
  for (let i = 0; i <= 59; i++) {
    seconds.value.push(String(i).padStart(2, "0"));
  }
};

// 日期选择器变化
const onDatePickerChange = (e) => {
  datePickerValue.value = e.detail.value;
  const year = years.value[e.detail.value[0]];
  const month = months.value[e.detail.value[1]];
  updateDays(year, parseInt(month));
};

// 时间选择器变化
const onTimePickerChange = (e) => {
  timePickerValue.value = e.detail.value;
};

// 显示开始日期选择器
const showStartDatePicker = () => {
  currentDateField.value = "startDate";
  datePickerRef.value?.open();
};

// 显示开始时间选择器
const showStartTimePicker = () => {
  currentTimeField.value = "startTime";
  timePickerRef.value?.open();
};

// 显示结束日期选择器
const showEndDatePicker = () => {
  currentDateField.value = "endDate";
  datePickerRef.value?.open();
};

// 显示结束时间选择器
const showEndTimePicker = () => {
  currentTimeField.value = "endTime";
  timePickerRef.value?.open();
};

// 重置日期选择器
const resetDatePicker = () => {
  const currentDate = new Date();
  const currentYear = currentDate.getFullYear();
  const currentMonth = currentDate.getMonth() + 1;
  const currentDay = currentDate.getDate();

  const yearIndex = years.value.indexOf(currentYear);
  const monthIndex = months.value.indexOf(
    String(currentMonth).padStart(2, "0"),
  );
  const dayIndex = days.value.indexOf(String(currentDay).padStart(2, "0"));

  datePickerValue.value = [yearIndex, monthIndex, dayIndex];
};

// 重置时间选择器
const resetTimePicker = () => {
  timePickerValue.value = [0, 0, 0];
};

// 确认日期
const confirmDate = () => {
  const year = years.value[datePickerValue.value[0]];
  const month = months.value[datePickerValue.value[1]];
  const day = days.value[datePickerValue.value[2]];
  const dateString = `${year}-${month}-${day}`;

  if (currentDateField.value === "startDate") {
    startDate.value = dateString;
  } else if (currentDateField.value === "endDate") {
    endDate.value = dateString;
  }

  datePickerRef.value?.close();
};

// 确认时间
const confirmTime = () => {
  const hour = hours.value[timePickerValue.value[0]];
  const minute = minutes.value[timePickerValue.value[1]];
  const second = seconds.value[timePickerValue.value[2]];
  const timeString = `${hour}:${minute}:${second}`;

  if (currentTimeField.value === "startTime") {
    startTime.value = timeString;
  } else if (currentTimeField.value === "endTime") {
    endTime.value = timeString;
  }

  timePickerRef.value?.close();
};

// 选择类型
const selectType = (type) => {
  selectedType.value = type;
};

// 返回
const goBack = () => {
  uni.navigateBack();
};

// 重置
const handleReset = () => {
  startDate.value = "";
  startTime.value = "";
  endDate.value = "";
  endTime.value = "";
  email.value = "";
  selectedType.value = "订单";

  uni.showToast({
    title: "已重置",
    icon: "none",
  });
};

// 提交
const handleSubmit = () => {
  // 验证
  if (!startDate.value || !startTime.value) {
    uni.showToast({
      title: "请选择开始日期和时间",
      icon: "none",
    });
    return;
  }

  if (!endDate.value || !endTime.value) {
    uni.showToast({
      title: "请选择结束日期和时间",
      icon: "none",
    });
    return;
  }

  if (!email.value) {
    uni.showToast({
      title: "请输入接收邮箱",
      icon: "none",
    });
    return;
  }

  // 邮箱格式验证
  const emailRegex = /^[^\s@]+@[^\s@]+\.[^\s@]+$/;
  if (!emailRegex.test(email.value)) {
    uni.showToast({
      title: "请输入正确的邮箱格式",
      icon: "none",
    });
    return;
  }

  // 提交数据
  const data = {
    startDateTime: `${startDate.value} ${startTime.value}`,
    endDateTime: `${endDate.value} ${endTime.value}`,
    email: email.value,
    type: selectedType.value,
  };

  console.log("提交数据:", data);

  uni.showToast({
    title: "创建成功",
    icon: "none",
  });

  // 延迟返回
  setTimeout(() => {
    uni.navigateBack();
  }, 1500);

  // TODO: 实际提交到服务器
};

// 初始化
initDateData();
initTimeData();
</script>

<style lang="scss" scoped>
.page-container {
  min-height: 100vh;
  background-color: #f5f5f5;
  display: flex;
  flex-direction: column;
}

.content {
  flex: 1;
  padding: 20rpx 30rpx;
  //margin-top: 88rpx;
}

// 表单容器
.form-container {
  background-color: #fff;
  border-radius: 16rpx;
  overflow: hidden;
  margin-bottom: 20rpx;
}

// 表单项
.form-item {
  display: flex;
  align-items: center;
  justify-content: space-between;
  padding: 32rpx 30rpx;
  border-bottom: 1rpx solid #f0f0f0;

  &:last-child {
    border-bottom: none;
  }

  &:active {
    background-color: #f9f9f9;
  }
}

.input-item {
  &:active {
    background-color: transparent;
  }
}

.form-label {
  font-size: 28rpx;
  color: #333;
  min-width: 140rpx;
}

.form-value {
  display: flex;
  align-items: center;
  gap: 8rpx;
  flex: 1;
  justify-content: flex-end;

  text {
    font-size: 28rpx;
    color: #333;
  }

  .placeholder {
    color: #fabc02;
  }
}

.form-input {
  flex: 1;
  font-size: 28rpx;
  color: #333;
  text-align: right;
}

.input-placeholder {
  color: #999;
}

// 数据类型选择
.type-section {
  background-color: #f8f8f8;
}

.type-item {
  display: flex;
  align-items: center;
  justify-content: space-between;
  padding: 32rpx 30rpx;
  background-color: #fff;
  border-bottom: 1rpx solid #f0f0f0;

  &:last-child {
    border-bottom: none;
  }

  &.active {
    background-color: #fffbf0;

    .type-text {
      color: #fabc02;
      font-weight: 600;
    }
  }

  &:active {
    opacity: 0.8;
  }
}

.type-text {
  font-size: 28rpx;
  color: #333;
}

// 底部按钮
.bottom-actions {
  display: flex;
  gap: 20rpx;
  padding: 20rpx 0;
}

.action-btn {
  flex: 1;
  height: 88rpx;
  border-radius: 50rpx;
  display: flex;
  align-items: center;
  justify-content: center;

  text {
    font-size: 32rpx;
    font-weight: 600;
  }

  &:active {
    opacity: 0.8;
  }
}

.reset-btn {
  background-color: #fff;
  border: 2rpx solid #ff9900;

  text {
    color: #ff9900;
  }
}

.submit-btn {
  background-color: #ff9900;

  text {
    color: #fff;
  }
}

// 选择器容器
.picker-container {
  background-color: #fff;
  border-radius: 20rpx 20rpx 0 0;
  padding-bottom: env(safe-area-inset-bottom);
}

.picker-header {
  display: flex;
  align-items: center;
  justify-content: space-between;
  padding: 24rpx 30rpx;
  border-bottom: 1rpx solid #f0f0f0;
}

.picker-reset {
  font-size: 28rpx;
  color: #666;

  &:active {
    opacity: 0.6;
  }
}

.picker-confirm {
  font-size: 28rpx;
  color: #fabc02;

  &:active {
    opacity: 0.6;
  }
}

.picker-title {
  font-size: 32rpx;
  font-weight: 600;
  color: #333;
}

.picker-view {
  height: 400rpx;
  width: 100%;
}

.picker-item {
  display: flex;
  align-items: center;
  justify-content: center;
  height: 68rpx;
  font-size: 28rpx;
  color: #333;
}
</style>
